angular
	.module("userModule", [
		"utilsModule"
	])
    .service("userDataPool",[
        "sanHttp",
        "urlPrefix",
        function(sanHttp, urlPrefix){
            var serv = this;

            serv.register = register;
            serv.detectTel = detectTel;
            serv.detectCode = detectCode;
            serv.detectLoginName = detectLoginName;
            serv.login = login;

            function register(req){
                return sanHttp
                    .http({
                        url: "/web/registerForPerson",
                        urlPrefix: urlPrefix,
                        method: "post",
                        data: req
                    })
            }

            function detectTel(req){
                return sanHttp
                    .http({
                        url: "/web/validatePhone",
                        urlPrefix: urlPrefix,
                        method: "post",
                        data: req
                    })
            }

            function detectCode(req){
                return sanHttp
                    .http({
                        url: "/web/validateInvitationCode",
                        urlPrefix: urlPrefix,
                        method: "post",
                        data: req
                    })
            }

            function detectLoginName(req){
                return sanHttp
                    .http({
                        url: "/web/validateLoginName",
                        urlPrefix: urlPrefix,
                        method: "post",
                        data: req
                    })
            }

            function login(req){
                return sanHttp
                    .http({
                        url: "/web/login",
                        urlPrefix: urlPrefix,
                        method: "post",
                        data: req
                    })
            }
        }
    ])
	.component("userLogin", {
		bindings: {},
		controller: "userLoginCtrl",
		controllerAs: "ulc",
		templateUrl: "../html/user/userLogin.html"
	})
	.controller("userLoginCtrl", [
		"sanHttp",
		"commonUtils",
		"$q",
        "userDataPool",
        "$scope",
        "$document",
        "SAN_GLOBAL",
		function (sanHttp, commonUtils, $q, userDataPool, $scope, $document, SAN_GLOBAL) {
			var
				_vm_ = this;

            if(SAN_GLOBAL.userLoginInfo){
                userDataPool.login(SAN_GLOBAL.userLoginInfo);
            }

			_vm_.$onInit = $onInit;

			_vm_.showMenu = showMenu;

			function $onInit() {
				_vm_.status = {
					isLogined: false,
					isLogining: false,
					isShowMenu: false
				};
				_vm_.userInfo = {
					name: SAN_GLOBAL.userBaseInfo && SAN_GLOBAL.userBaseInfo.userName || "你好", 
					icon: SAN_GLOBAL.userBaseInfo && SAN_GLOBAL.userBaseInfo.icon || "../res/img/ss.png"
				};

                _vm_.status.isLogined = SAN_GLOBAL.userBaseInfo ? true : false;
			}

            $document.bind("click", function(event) {
                _vm_.status.isShowMenu = false;
                $scope.$apply();             
            }); 

			function showMenu(e) {
                e.stopPropagation();
				_vm_.status.isShowMenu = !_vm_.status.isShowMenu;
				if (_vm_.status.isShowMenu) {
					_detectMenu()
						.then(function (menu) {
							_vm_.menu = menu;
						});
                }
			}

			function _detectMenu() {
				return $q(function (resolve, reject) {
					var menu = {
						userInfo: {
							name: "个人信息",
							clickFunc: showUserInfo,
							enable: false
						},
						changePassword: {
							name: "更改密码",
							// clickFunc: changePassword,
							enable: false
						},
						logout: {
							name: "注销",
							clickFunc: logout,
							enable: false
						},
						login: {
							name: "登陆",
							clickFunc: login,
							enable: false
						},
						register: {
							name: "注册",
							clickFunc: register,
							enable: false
						}
					};
					if (_vm_.status.isLogined) {
						menu.userInfo.enable = true;
						menu.changePassword.enable = true;
						menu.logout.enable = true;
					} else {
						menu.login.enable = true;
						menu.register.enable = true;
					};
					resolve(menu);
				});
			}

            // 打开个人信息
			function showUserInfo() {
				commonUtils
					.openModal({
						controller: userInfoCtrl,
						templateUrl: "../html/userInfo/userInfo.html",
						size: "md",
						resolve: {
							userInfo: function () {
								return "holy shit";
							}
						}
					});
			}

            userInfoCtrl.$inject = [
                "userInfo",
                "$scope"
            ]

            function userInfoCtrl(userInfo, $scope){
			    var _vm_ = this;

                $onInit();

                _vm_.cancel = cancel;
                _vm_.confirm = confirm;

                function $onInit(){
                    console.log("初始化Modal");
                     _vm_.userInfo = userInfo;
                }   

                function confirm(){
                   $scope.$close("选中关闭");
                }

                function cancel(){
                    $scope.$dismiss();
                }
            }

            // 注册逻辑
            function register(){
                commonUtils
					.openModal({
						controller: registerCtrl,
						templateUrl: "../html/register/register.html",
						size: "md",
						resolve: {}
					});
            }

            registerCtrl.$inject = [
                "$scope",
                "userDataPool"
            ]

            function registerCtrl($scope, userDataPool){
                var 
                    _vm_ = this
                ;

                init();

                _vm_.confirm = confirm;
                _vm_.cancel = cancel;

                function init(){
                    _vm_.registerInfo = {
                        userName: "",
                        tel : "",
                        code: "",
                        idCard: "",
                        loginName: "",
                        address: "",
                        eMail: "",
                        password: ""
                    };
                    _vm_.status = {
                        isFetching: false
                    };
                    _vm_.labelList = [
                        {
                            name: "姓名",
                            model: "modal.registerInfo.userName",
                            indispensable : true
                        },
                        {
                            name: "电话号码",
                            model: "modal.registerInfo.tel",
                            indispensable: true,
                            detect: true,
                            detectFunc: _detectTel
                        },
                        {
                            name: "邀请码",
                            model: "modal.registerInfo.code",
                            indispensable: true,
                            detect: true,
                            detectFunc: _detecCode
                        },
                        {
                            name: "身份证号码",
                            model: "modal.registerInfo.idCard",
                            indispensable: false
                        },
                        {
                            name: "登陆名",
                            model: "modal.registerInfo.loginName",
                            indispensable: true,
                            detect: true,
                            detectFunc: _detectLoginName
                        },
                        {
                            name: "地址",
                            model: "modal.registerInfo.address",
                            indispensable: false
                        },
                        {
                            name: "电子邮箱",
                            model: "modal.registerInfo.eMail",
                            indispensable: false
                        },
                        {
                            name: "登陆密码",
                            model: "modal.registerInfo.password",
                            indispensable: true
                        }
                    ];
                    _vm_.keyArr = Object.keys(_vm_.registerInfo);
                }

                function confirm(){
                    userDataPool.register(_vm_.registerInfo);
                    $scope.$close();
                }

                function cancel(){
                    $scope.$dismiss();
                }

                function _detectTel(){
                    userDataPool.detectTel({
                        tel: _vm_.registerInfo.tel
                    })
                    .then(function(data){
                        _vm_.labelList[1].alertMessage = data.message;
                    })
                }
                
                function _detecCode(){
                    userDataPool.detectCode({
                        code: _vm_.registerInfo.code
                    })
                    .then(function(data){
                        _vm_.labelList[2].alertMessage = data.message;
                    });
                }

                function _detectLoginName(){
                    userDataPool.detectLoginName({
                        loginName: _vm_.registerInfo.loginName 
                    })
                    .then(function(data){
                        _vm_.labelList[4].alertMessage = data.message;
                    });
                }
            }

            // 登陆逻辑
            function login(){
                commonUtils
					.openModal({
						controller: loginCtrl,
						templateUrl: "../html/login/login.html",
						size: "md",
						resolve: {}
					})
                    .result
                    .then(function(userInfo){
                        _vm_.status.isLogined = true;
                        console.log(userInfo);
                        _vm_.userInfo = {
                            name: userInfo.userBaseInfo.userName,
                            icon: userInfo.userBaseInfo.icon || "../res/img/ss.png" 
                        }
                    });
            }

            loginCtrl.$inject = [
                "$scope",
                "userDataPool",
                "SAN_GLOBAL"
            ]

            function loginCtrl($scope, userDataPool, SAN_GLOBAL){
                var 
                    _vm_ = this;

                _vm_.confirm = confirm;
                _vm_.cancel = cancel;

                init();

                function init(){
                    _vm_.loginInfo = {
                        loginName: "",
                        password: ""
                    }
                    _vm_.labelList = [
                        {
                            name: "用户名：",
                            model: "modal.loginInfo.loginName"
                        },
                        {
                            name: "密码：",
                            model: "modal.loginInfo.password",
                            type: "password"
                        }
                    ];
                    _vm_.keyArr = Object.keys(_vm_.loginInfo);
                }

                function confirm(){
                    userDataPool
                        .login(_vm_.loginInfo)
                        .then(function(data){
                            if(data.status == 0){
                                return;
                            }else{
                                SAN_GLOBAL.setKeyInLocalStorage("userBaseInfo", data.data);
                                SAN_GLOBAL.setKeyInLocalStorage("userLoginInfo", _vm_.loginInfo);
                                SAN_GLOBAL.init();
                                $scope.$close({
                                    userBaseInfo: data.data
                                });
                            }
                        })
                    ;
                }

                // function forget(){
                //      _vm_.labelList = [
                //         {
                //             name: "用户名：",
                //             model: "modal.loginInfo.loginName"
                //         },
                //         {
                //             name: "密码：",
                //             model: "modal.loginInfo.password",
                //             type: "password"
                //         }
                //     ];
                // }

                function cancel(){
                    $scope.$dismiss();
                }
                
            }

            // 注销
            function logout(){
                SAN_GLOBAL.destroy();
                _vm_.status.isLogined = false;
                _vm_.userInfo = {
                    name: "请登录",
                    icon: "../res/img/ss.png"
                }
            }
		}
	]);
